import {
  View,
  Text,
  Image,
  Checkbox,
  ScrollView,
  Button,
  Picker,
  Input,
} from "@tarojs/components";
import Taro, { useLoad,useDidShow } from "@tarojs/taro";
import "./index.scss";
import { useState, useMemo, useCallback, useEffect } from "react";
import {
  AtIcon,
  AtActionSheet,
  AtActionSheetItem,
  AtModal,
  AtModalHeader,
  AtModalContent,
  AtModalAction,
  AtList,
  AtListItem,
} from "taro-ui";
// 引入头图
import headerPng from "../../assets/images/insureheadpic.png";
import GetMorePointsModal from "../../components/GetMorePointsModal";
import { request } from "@/utils/request";
import { markPhone, getRoleName } from "@/utils/tools";
import { getGlobalData } from "@/globalData";
const productId = getGlobalData('jifenBaoProductId');
export default function AddInsurance() {
  // 被保人列表
  const [headerImg,setHeaderImg] = useState(headerPng);
  const [needFenNum,setNeedFenNum] = useState<number>(0);

  const [insuranceDetail, setInsuranceDetail] = useState<any>({
    insurances:[]
  });
  const [isAgreeAgreement, setIsAgreeAgreement] = useState(false);
  const familyPointsNum = Number(Taro.getStorageSync("familyPointsNum")) || 0;


  const [insufficientPointsModalVisible, setInsufficientPointsModalVisible] = useState(false);
  
  const [insufficientPoints, setInsufficientPoints] = useState(false);

  const [familyList, setFamilyList] = useState<
    {
      userId: number;
      name: string;
      availability: number;
    }[]
  >([]);

  // 被选中的被保人
  const [selectedFamilyMember, setSelectedFamilyMember] = useState<{
    userId: number;
    name: string;
    availability: number;
  }>();
  // 被选中的带身份证信息的被保人
  const [selectedFamilyMemeberIdCardInfo,setSelectedFamilyMemeberIdCardInfo] = useState<{
    userId: number;
    name: string;
    idcard: string;
    status: number;
  }>({
    userId: 0,
    name: "",
    idcard: "",
    status: 0,
  });
  const hasAvaiablePerson = useMemo(()=>{
    return familyList.filter(item=>item.availability).length > 0
  },[familyList])
  

  const [pickerFamilyActionSheetVisible, setPickerFamilyActionSheetVisible] =
    useState(false);

  function changeSelectedFamilyPersonIdcard(idcard) {
    // console.log("changeSelectedFamilyPersonIdcard idcard:", idcard);
    if(selectedFamilyMemeberIdCardInfo.status ===1){
      Taro.showToast({ title: "该用户已实名认证", icon: "none" });
      return 
    }
    setSelectedFamilyMemeberIdCardInfo(perv=>{
      return {
        ...perv,
        idcard
      }
    })
  }

  function showAgreement() {
    let articleIds = insuranceDetail.insurances
      .map((item) => {
        let lastIndex = item.url.lastIndexOf('/')
        return item.url.slice(lastIndex + 1).replace(/\D*/, '')
      })
      .filter((item) => {
        return !!item
      })
      .join(',')
      Taro.navigateTo({
        url: '/pages/agreeAgreement/index?articleIds=' + articleIds
      })
  }

  function changeSelectedFamilyPersonName(name) {
    if(selectedFamilyMemeberIdCardInfo.status ===1){
      Taro.showToast({ title: "该用户已实名认证", icon: "none" });
      return 
    }
    
    setSelectedFamilyMemeberIdCardInfo(perv=>{
      return {
        ...perv,
        name: name
      }
    })
  }
 
  function pickFamilyMember(item) {
    console.log("item:", item);
    if(item.availability){
      setSelectedFamilyMember(item)
      getUserInfo(item.userId)
      setPickerFamilyActionSheetVisible(false)
      // checkUserPoints(item.userId)
    }
    
  }
  // 获取用户实名信息
  function getUserInfo(id: number) {
    // 这个接口不返回用户id
    request({
      url: "/api/queryUserCertification?userId=" + id,
      success: (res) => {
       
        setSelectedFamilyMemeberIdCardInfo({
          name:res.name || '',
          idcard:res.idcard || '',
          userId: id,
          status: res.status || 0,
        });
      },
    });
  }
  // 查询积分扣减情况
  function checkUserPoints(userId){
    request({
      url: `/api/points/family/getRedemptionRecord/${userId}/${productId}`,
      data: {
        token: Taro.getStorageSync("token"),
        openId: Taro.getStorageSync("openid"),
      },
      success: (data) =>{
        console.log('data:',data)
      }
    })
  }
  // 获取家庭组
  useLoad(() => {
    // 获取被保人列表
    request({
      url: "/api/points/family/queryFamilyInsurance?productId=" + productId,
      data: {
        token: Taro.getStorageSync("token"),
        openId: Taro.getStorageSync("openid"),
      },
      success(data) {
        // console.log("MyFamilyGroup respDataList:", respDataList);
        setFamilyList(data);
      },
    });
    // 获取保险详情
    request({
      url: "/api/queryGoldProduct/" + productId,
      success: (data) => {
        console.log('insuranceDetail data:',data)
        setInsuranceDetail(data);
        setNeedFenNum(data.goldValue)
        setHeaderImg(data.productCover)
        setInsufficientPoints(familyPointsNum < data.goldValue)
      },
    });
  });
  useDidShow(()=>{
    let agree = Taro.getStorageSync("pages/agreeAgreement/index/agreeInsuranceAgreement")
    setIsAgreeAgreement(agree|| false)
  })

  function jumpDetailPage() {
    Taro.navigateTo({
      url: "/pages/insuranceDetail/index",
    });
  }
  // 用户实名校验
  function validateUserCert() {
    return new Promise((resolve) => {
      request({
        url:
          '/api/userCertification?userId=' +
          selectedFamilyMemeberIdCardInfo.userId +
          '&name=' +
          selectedFamilyMemeberIdCardInfo.name +
          '&idcard=' +
          selectedFamilyMemeberIdCardInfo.idcard,
        method: 'POST',

        success: (res) => {
          console.log('validateUserCert res；', res)
          resolve(true)
        },
        fail: (code, msg, failData) => {
          console.log('validateUserCert fail；', code, msg, failData)
          Taro.showModal({
            title: '提示',
            content:failData.respData || '实名认证失败，请重新输入',
            confirmText: '好的'
          })
          resolve(false)
        }
      })
    })
  }
 
  const handleSubmit = async () => {
    if(!selectedFamilyMember || selectedFamilyMember.name ===''){
      Taro.showModal({
        title: "提示",
        content: "请选择被保障人",
      });
      return 
    }
    // 提交逻辑
    if (!isAgreeAgreement) {
      Taro.showModal({
        title: "提示",
        content: "请阅读并同意相关协议",
      });
      return;
    }
    if(!hasAvaiablePerson){
      Taro.showModal({
        title: "提示",
        content: "没有符合领取条件的被保障人",
      });
      return;
    }
    if(insufficientPoints){
      Taro.showModal({
        title: "提示",
        content: "积分不足，无法领取",
      });
      return;
    }
    // 还未实名认证
    if(selectedFamilyMemeberIdCardInfo.status !==1){
      if(selectedFamilyMemeberIdCardInfo.name === ''){
        Taro.showModal({
          title: "提示",
          content: "请输入被保障人姓名",
        });
        return;
      }
      if(selectedFamilyMemeberIdCardInfo.idcard === ''){
        Taro.showModal({
          title: "提示",
          content: "请输入被保障人身份证号",
        });
        return;
      }
      let idCard = selectedFamilyMemeberIdCardInfo.idcard
      if (!/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(idCard)) {
        Taro.showToast({
          title: '身份证号格式错误',
          icon: 'none'
        })
        return
      }
      let certRes = await validateUserCert()
      if (!certRes) {
        return
      }else {
        setSelectedFamilyMemeberIdCardInfo(perv=>{
          return {
            ...perv,
            status:1
          }
        })
      }
    }
    // 判断积分是否充足
    let userId = selectedFamilyMemeberIdCardInfo.userId
    request({
      url:
        `/api/goldProduct/${productId}/redeeming?clientType=2&userId=` + userId+'&pointsFlag=true',
      method: 'POST',
      data: {
        userId: userId,
        id: productId,
        clientType: 2,
        pointsFlag:true,
      },
      success: (res) => {
        console.log('redeeming:', res)
        Taro.showModal({
          title: '提示',
          content: '兑换成功',
          confirmText: '好的',
          success: (res) =>{
            Taro.reLaunch({
              url:'/pages/index/index'
            })
          }
        })
      },
      fail: (err) => {
        console.log('redeeming err:', err)
        Taro.showModal({
          title: '提示',
          content: '兑换失败，请重试',
          confirmText: '好的',
          success: (res) =>{
           
          }
        })
      }
    })


    
    
    
  };
  return (
    <View className="addInsurance">
      <View className="header">
        <Image className="header-image" src={headerImg} mode="widthFix"></Image>
        <View className="detail-btn" onClick={jumpDetailPage}>
          查看详情
        </View>
      </View>
      <View className="bodyer">
        <View className="points">
          <Text className="num">{needFenNum}</Text>
          <Text className="txt">万户分/份</Text>
        </View>
        <View className="condition">
          <View className="condition-item">
            <View className="cond-title">
              <View className="num">1</View>
              <View className="title">被保障人</View>
            </View>
            
            <View className="form">
              <View className="form-item underline">
                <View className="form-label">选择被保障人:</View>
                <View className="form-value form-flex" onClick={()=>{
                  setPickerFamilyActionSheetVisible(true)
                }}>
                  {(selectedFamilyMember &&selectedFamilyMember.name) ? <Text className='name'>{selectedFamilyMember.name}</Text> : <Text className='placeholder'>请选择被保障人</Text>}
                  <AtIcon
                    className="form-icon"
                    size="10"
                    value="chevron-right"
                    color="#999"
                  ></AtIcon>
                </View>
              </View>
              <View className="form-item underline">
                <View className="form-label">姓名:</View>
                <View className="form-value">
                  <Input
                    className='input'
                    type="text"
                    placeholder="请输入姓名"
                    value={selectedFamilyMemeberIdCardInfo.name}
                    onInput={(event)=>{changeSelectedFamilyPersonName(event.detail.value)}}
                    disabled={
                      selectedFamilyMemeberIdCardInfo.status === 1 ||
                      !hasAvaiablePerson
                    }
                  />
                </View>
              </View>
              <View className="form-item underline">
                <View className="form-label">身份证</View>
                <View className="form-value">
                  <Input
                    className='input'
                    type="text"
                    placeholder="请输入身份证号码"
                    value={selectedFamilyMemeberIdCardInfo.idcard}
                    onInput={(event)=>{changeSelectedFamilyPersonIdcard(event.detail.value)}}
                    disabled={
                      selectedFamilyMemeberIdCardInfo.status === 1 ||
                      !hasAvaiablePerson
                    }
                  />
                </View>
              </View>
              {/* <View className="form-item ">
                <View className="form-tip">
                  <Checkbox className='form-checkbox' value="选中" checked={isAgreeAgreement}>
                  </Checkbox>
                  <Text className="form-tip-text">
                    我已阅读并同意
                    {insuranceDetail.insurances.map(item=>{
                      return <Text className='agreement' onClick={showAgreement}>《{item.name}》</Text>
                    })}
                  </Text>
                </View>
              </View> */}
            </View>
           
          </View>

          <View className="condition-item">
            <View className="cond-title">
              <View className="num">2</View>
              <View className="title">所需积分</View>
            </View>
            <View className="jifen">
              <View className="insure-num">1</View>
              <View className="insure-info">份，合计需要：</View>
              <View className="insure-total">{ needFenNum}</View>
              <View className="insure-info"> 万户分</View>
            </View>
            <View className="jifen-danger">
              {insufficientPoints && (
                <>
                  <View className="insure-danger-tip">
                    积分不足！当前仅有{familyPointsNum}分
                  </View>
                </>
              )}
            </View>
          </View>
        </View>
    
        <View className="agree">
          <AtIcon
            className="raido"
            value="check-circle"
            size="12"
            color={isAgreeAgreement ? "#F00" : "#999"}
            onClick={() => setIsAgreeAgreement(!isAgreeAgreement)}
          ></AtIcon>
           <View className="agree-info">
            <Text className="agree-des">我已阅读并同意</Text>
            {/* <Text className="agree-primary">《万户健康公益项目服务协议》</Text>
            <Text className="agree-des">及</Text>
            <Text className="agree-primary">《授权委托书》</Text> */}
            {insuranceDetail.insurances.map(item=>{
                return <Text className='agree-primary' onClick={showAgreement}>《{item.name}》</Text>
              })}
          </View> 
        </View> 
        <View
          onClick={handleSubmit}
          className={["agree-btn", insufficientPoints ? "disabled" : ""].join(
            " "
          )}
        >
          同意条款并领取
        </View>
      </View>
      <AtModal isOpened={insufficientPointsModalVisible}>
        <AtModalHeader>积分不足</AtModalHeader>
        <AtModalContent>您当前积分不足，无法领取，请获取更多积分后重试</AtModalContent>
        <AtModalAction>
          <Button
            onClick={() => {
              setInsufficientPointsModalVisible(false);
            }}
          >
            返回
          </Button>
          {/* <Button
            onClick={() => {
              setInsufficientPointsModalVisible(false);
            }}
          >
            获取更多积分
          </Button> */}
        </AtModalAction>
      </AtModal>
      
      <AtActionSheet isOpened={pickerFamilyActionSheetVisible} cancelText="取消" title="请选择被保障人" onClose={()=>{setPickerFamilyActionSheetVisible(false)}} onCancel={()=>{setPickerFamilyActionSheetVisible(false)}}>
        {familyList.map((item) => {
          return (
            <AtActionSheetItem
              onClick={() => {
                pickFamilyMember(item);
              }}
            >
              <Text className={[item.availability ===1 ? '' : 'disabled'].join(' ')}>{item.name}</Text>
            </AtActionSheetItem>
          );
        })}
      </AtActionSheet>
    </View>
  );
}
